#include "kernel/types.h"
#include "kernel/stat.h"
#include "kernel/fcntl.h"
#include "kernel/param.h"
#include "user/user.h"


int
main(int argc, char *argv[])
{

  if(argc <= 2){
    printf("xargs: read error\n");
    exit(0);
  }

  char *p[MAXARG];
  for(int i=1; i<argc; i++){
    // printf("argc[%d], argv[%s]\n",i,argv[i]);
    p[i-1] = argv[i];
  }
  p[argc-1] = malloc(sizeof(char)*512); // 从标准输入读入参数
  
  p[argc] = 0;  // 参数结束标志

  int n;
  while( (n = read(0, p[argc-1], 512) ) > 0){
    int pid = fork();
    if (pid == 0) {
      p[argc-1][n-1] = 0; // 去掉换行符
      exec(argv[1], p);
    }else if (pid > 0){
      wait(0);
    }else {
      printf("xargs: fork error\n");
    }
    
  }
  
  if(n < 0){
    printf("xargs: read error\n");
    exit(1);
  }

  exit(0);
}
